package com.lyf.boot.modules.index.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.lyf.boot.annotation.Crypto;
import com.lyf.boot.base.system.entity.SysClient;
import com.lyf.boot.constant.Constant;
import com.lyf.boot.core.model.LoginBody;
import com.lyf.boot.core.model.LoginVo;
import com.lyf.boot.core.model.R;
import com.lyf.boot.core.service.IAuthStrategy;
import com.lyf.boot.modules.system.service.ISysClientService;
import com.lyf.boot.utils.AuthUtil;
import com.lyf.boot.utils.JsonUtil;
import com.lyf.boot.utils.ValidatorUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 授权接口
 * @author Luyufan
 * @date 2023/7/5 10:20
 */
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Slf4j
public class AuthController {

    private final ISysClientService sysClientService;

    /**
     * 登录接口
     * @param body 登录参数
     * @return 登录结果
     */
    @PostMapping("/login")
    @Crypto(inDecode = false)
    public R<LoginVo> login(@RequestBody String body){
        LoginBody loginBody = JsonUtil.parseObject(body, LoginBody.class);
        if(null == loginBody){
            return R.fail("登录参数不能为空");
        }
        ValidatorUtil.validate(loginBody);
        String clientCode = loginBody.getClientCode();
        String grantType = loginBody.getGrantType();
        SysClient client = sysClientService.getSysClientByCoe(clientCode);
        // 查询不到 client 或 client 内不包含 grantType
        if (ObjectUtil.isNull(client) || !CollUtil.contains(StrUtil.splitTrim(client.getGrantType(),StrUtil.COMMA), grantType)) {
            log.info("客户端Code: {} 认证类型：{} 异常!.", clientCode, grantType);
            return R.fail("认证权限类型错误");
        } else if (!Constant.ONE.equals(client.getStatus())) {
            return R.fail("认证权限类型已禁用");
        }
        // 登录
        LoginVo loginVo = IAuthStrategy.login(body, client, grantType);
        return R.ok(loginVo);
    }

    /**
     * 注销登录
     * @return
     */
    @PostMapping("/logout")
    public R<Void> logout(){
        AuthUtil.logout();
        return R.ok();
    }
}
